package cumeo89.chii.client.ui;

import com.google.gwt.user.client.ui.Widget;

import cumeo89.chii.client.util.MyArrays;

public class NamedPanelHelper {

	public NamedPanelHelper(ExtendedPanel panel, String[] names) {
		this.panel = panel;
		this.names = names;
		this.children = new Widget[names.length];
	}

	private ExtendedPanel panel;
	private String[] names;
	private Widget[] children;

	public void setWidget(String name, Widget widget) {
		int i = MyArrays.search(names, name);
		if (i < 0) {
			throw new UnsupportedOperationException();
		}
		if (children[i] != null) {
			panel.remove(children[i]);
		}
		children[i] = widget;
		int beforeCount = 0;
		for (int j = 0; j < i; j++) {
			if (children[j] != null) {
				beforeCount++;
			}
		}
		if (widget != null) {
			panel.insert(widget, beforeCount);
		}
	}

	public Widget removeWidget(String name) {
		int i = MyArrays.search(names, name);
		if (i < 0) {
			throw new UnsupportedOperationException();
		}
		if (children[i] != null) {
			Widget removed = children[i];
			panel.remove(children[i]);
			children[i] = null;
			return removed;
		}
		return null;
	}

}
